package com.adinnet.admin.child.controller;


import com.adinnet.admin.child.model.Child;
import com.adinnet.admin.child.model.form.ChildForm;
import com.adinnet.admin.child.model.form.ChildRankForm;
import com.adinnet.admin.child.model.vo.ChildRank;
import com.adinnet.admin.child.model.vo.ChildReq;
import com.adinnet.admin.child.model.vo.ChildResp;
import com.adinnet.admin.child.service.ChildService;
import com.adinnet.admin.classs.model.Classs;
import com.adinnet.admin.classs.service.ClasssService;
import com.adinnet.admin.common.service.CommonService;
import com.adinnet.admin.content.model.Content;
import com.adinnet.admin.organization.model.Organization;
import com.adinnet.admin.organization.service.OrganizationService;
import com.adinnet.admin.school.model.School;
import com.adinnet.admin.school.service.SchoolService;
import com.adinnet.admin.system.model.SysUser;
import com.adinnet.admin.system.model.vo.SysUserInfo;
import com.adinnet.admin.user.model.User;
import com.adinnet.admin.user.service.UserService;
import com.adinnet.common.upload.UploadUtils;
import com.adinnet.core.JsonResult;
import com.adinnet.core.PageResult;
import com.adinnet.core.exception.BizException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.ConnectionUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 儿童表 前端控制器
 * </p>
 *
 * @author zYshuai
 * @since 2020-12-11
 */
@RestController
@RequestMapping("admin/child")
public class ChildController {

    @Autowired
    protected HttpServletRequest request;
    @Autowired
    protected HttpServletResponse response;

    @Autowired
    private ChildService childService;

    @Autowired
    private OrganizationService organizationService;

    @Autowired
    private CommonService commonService;

    @Autowired
    private SchoolService schoolService;

    @Autowired
    private ClasssService classsService;

    @Autowired
    private UserService userService;


    /**
     * 学员页面
     * 1，返回用户可查询的机构列表
     * 2，返回用户可查询的校区列表
     * 3，返回用户可查询的班级列表
     * @param model
     * @return
     */
    @GetMapping()
    public ModelAndView child(Model model){
        SysUserInfo sysUserInfo=commonService.getLoginUser();
        model.addAttribute("organizationsList", organizationService.getListByUserRole(sysUserInfo));
        model.addAttribute("schoolList", schoolService.getListByUserRole(sysUserInfo));
        model.addAttribute("classsList", classsService.getListByUserRole(sysUserInfo));
        return new ModelAndView("child/child.html");
    }


    /**
     * 学院列表
     * 默认页面
     * 1，超级管理员查所有
     * 2，机构查机构下的数据
     * 3，校区查校区的数据
     * 4，班级查班级的数据
     * @param childForm
     * @return
     */
    @GetMapping("/childList")
    public PageResult<ChildResp> list(ChildForm childForm) {
        SysUserInfo sysUser= commonService.getLoginUser();
        //默认页面处理和重置搜索的处理
        if(childForm.getClassId()==null&&childForm.getOrganizationId()==null&&childForm.getSchoolId()==null){
            if(sysUser!=null){
                switch (sysUser.getMaxRole()){
                    case "admin":
                        break;
                    case "organization":
                        childForm.setOrganizationId(sysUser.getOrganizationId());
                        break;
                    case "school":
                        childForm.setSchoolId(sysUser.getSchoolId());
                        break;
                    case "classs":
                        childForm.setSysUserId(sysUser.getId());
                        break;
                    default:
                        break;
                }
            }
        }
        return childService.queryChildList(childForm);
    }

    /**
     * 排行榜页面
     * 1，返回用户可查询的机构列表
     * 2，返回用户可查询的校区列表
     * 3，返回用户可查询的班级列表
     * @param model
     * @return
     */
    @GetMapping("rank")
    public ModelAndView rank(Model model){
        Boolean isAdmin=false;
        Boolean isSchool=false;
        Boolean isClasss=false;
        Boolean isOrganization=false;
        List<Organization> organizationsList = new ArrayList<>();
        List<School> schoolList = new ArrayList<>();
        List<Classs> classsList = new ArrayList<>();
        SysUser sysUser= commonService.getLoginUser();
        if(sysUser!=null){
            switch (((SysUserInfo) sysUser).getMaxRole()){
                case "admin":
                    isAdmin=true;
                    break;
                case "school":
                    isSchool=true;
                    break;
                case "classs":
                    isClasss=true;
                    break;
                case "organization":
                    isOrganization=true;
                    break;
                default:
                    break;
            }
        }
        if(isAdmin){ //超级管理员可以查看所有数据
            organizationsList=organizationService.list();
            schoolList=schoolService.list();
            classsList=classsService.list();
        }else if(isOrganization){  //机构管理员可以查看所属机构下的数据
            organizationsList=organizationService.list(new QueryWrapper<Organization>().eq("id",sysUser.getOrganizationId()).eq("deleted",0));
            schoolList=schoolService.list(new QueryWrapper<School>().eq("organization_id",sysUser.getOrganizationId()).eq("deleted",0));
            classsList=classsService.selectClasssByOrgId(sysUser.getOrganizationId());
        }else if(isSchool){  //（分校区管理员）仅能查看所属校区下的数据
            organizationsList=organizationService.list(new QueryWrapper<Organization>().eq("id",sysUser.getOrganizationId()).eq("deleted",0));
            schoolList=schoolService.list(new QueryWrapper<School>().eq("id",sysUser.getSchoolId()).eq("deleted",0));
            classsList=classsService.list(new QueryWrapper<Classs>().eq("school_id",sysUser.getSchoolId()).eq("deleted",0));
        }else if(isClasss){ //班级负责人账号仅能搜索到自己所带的班级的数据。
            organizationsList=organizationService.list(new QueryWrapper<Organization>().eq("id",sysUser.getOrganizationId()).eq("deleted",0));
            schoolList=schoolService.list(new QueryWrapper<School>().eq("id",sysUser.getSchoolId()).eq("deleted",0));
            classsList=classsService.list(new QueryWrapper<Classs>().eq("sys_user_id",sysUser.getId()).eq("deleted",0));
        }
        model.addAttribute("organizationsList",organizationsList);
        model.addAttribute("schoolList",schoolList);
        model.addAttribute("classsList",classsList);
        return new ModelAndView("rank/rank.html");
    }


    /**
     * 排行榜列表
     * 默认页面
     * 1，超级管理员查所有
     * 2，机构查机构下的数据
     * 3，校区查校区的数据
     * 4，班级查班级的数据
     * @param form
     * @return
     */
    @GetMapping("/rankList")
    public PageResult<ChildRank> list(ChildRankForm form) {
        SysUser sysUser= commonService.getLoginUser();
        //默认页面处理和重置搜索的处理
        if(form.getClassId()==null&&form.getOrganizationId()==null&&form.getSchoolId()==null){
            if(sysUser!=null){
                switch (((SysUserInfo) sysUser).getMaxRole()){
                    case "admin":
                        break;
                    case "organization":
                        form.setOrganizationId(sysUser.getOrganizationId());
                        break;
                    case "school":
                        form.setSchoolId(sysUser.getSchoolId());
                        break;
                    case "classs":
                        form.setSysUserId(sysUser.getId());
                        break;
                    default:
                        break;
                }
            }
        }
        return childService.queryRankList(form);
    }


    /**
     * 新增学员
     **/
    @ResponseBody
    @RequestMapping("add")
    public JsonResult add(ChildReq childReq, HttpServletRequest request) {
        try{
            User u=userService.getOne(new QueryWrapper<User>().eq("tel_no",childReq.getTelNo()).eq("deleted", 0));
            if(u!=null){
                return JsonResult.error("添加失败,手机号已存在注册用户");
            }
            Integer childId=childService.addNewChild(childReq);
            if(childId!=null&&childId.intValue()>0){
                commonService.saveOperation(request,"学员列表-新增学员,新增学员id为："+childId);
                return JsonResult.ok("添加成功");
            }else {
                return JsonResult.error("添加失败");
            }
        }catch (BizException e){
            return JsonResult.error("注册失败,发送短信失败");
        }
    }

    /**
     * 编辑儿童
     **/
    @ResponseBody
    @RequestMapping("update")
    public JsonResult update(ChildReq childReq, HttpServletRequest request) {
        try{
            Integer childId=childService.editChild(childReq);
            if(childId!=null&&childId.intValue()>0){
                commonService.saveOperation(request,"学员列表-编辑学员,编辑的学员id为："+childId);
                return JsonResult.ok("操作成功");
            }else {
                return JsonResult.error("操作失败");
            }
        }catch (BizException e){
            return JsonResult.error("编辑失败,发送短信失败");
        }
    }


    /**
     * 修改儿童账号状态
     **/
    @ResponseBody
    @RequestMapping("updateState")
    public JsonResult updateState(Integer childId, Integer state, HttpServletRequest request) {
        if (childId == null) {
            return JsonResult.error("参数childId不能为空");
        }
        if (state == null || (state != 0 && state != 1)) {
            return JsonResult.error("状态值不正确");
        }
        Child child = childService.getById(childId);
        User user = new User();
        user.setId(child.getUserId());
        user.setStatus(state);
        if(state==1){
            user.setDisableTime(new Date());
        }
        if(state==0){
            user.setEnableTime(new Date());
        }
        if (userService.updateById(user)) {
            commonService.saveOperation(request,"学员列表-修改学员账号状态,修改的学员为："+childId);
            return JsonResult.ok();
        } else {
            return JsonResult.error();
        }
    }


    /**
     * 批量删除儿童
     */
    @RequestMapping("deleteIds")
    @ResponseBody
    public JsonResult deleteIds(String childIds, HttpServletRequest request) {
        commonService.saveOperation(request,"学员列表-删除学员：删除的学员id为："+childIds);
        return childService.deleteIds(childIds);
    }

    /**
     * 导入儿童账号
     * @param file
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("/importChild")
    @Transactional(rollbackFor = Exception.class)
    public JsonResult importChild(@RequestParam(value = "file", required = false) MultipartFile file,HttpServletRequest request) throws Exception {
        //获取导入人的权限
        SysUser sysUser= commonService.getLoginUser();
        Integer organizationId=null;
        Integer schoolId=null;
        Integer sysUserId=null;
        //根据登陆人权限判断
        if(sysUser!=null){
            switch (((SysUserInfo) sysUser).getMaxRole()){
                case "admin":
                    break;
                case "organization":
                    organizationId=sysUser.getOrganizationId();
                    break;
                case "school":
                    schoolId=sysUser.getSchoolId();
                    break;
                case "classs":
                    sysUserId=sysUser.getId();
                    break;
                default:
                    break;
            }
        }

        List<Child> childList = new ArrayList<>();
        List<List<String>> list = UploadUtils.excelToList(file);
        List<String> failList = new ArrayList<>();
        list.remove(0);
        for (List<String> ls : list) {
            if(!StringUtils.isNotEmpty(ls.get(0)))throw new BizException("所有导入失败，有学生姓名为空,请检查后重试");
            if(StringUtils.isBlank(ls.get(2))||!StringUtils.isNumeric(ls.get(2)))throw new BizException("所有导入失败，有学生性别为空或格式错误,请检查后重试");
            if(!StringUtils.isNotEmpty(ls.get(3)))throw new BizException("所有导入失败，有所属校区为空,请检查后重试");
            if(!StringUtils.isNotEmpty(ls.get(4)))throw new BizException("所有导入失败，有所属班级为空,请检查后重试");
            if(!StringUtils.isNotEmpty(ls.get(5)))throw new BizException("所有导入失败，有学生手机号为空,请检查后重试");
            if(StringUtils.isBlank(ls.get(6))||!StringUtils.isNumeric(ls.get(6)))throw new BizException("所有导入失败，有学生学员分类为空或格式错误,请检查后重试");
            if(StringUtils.isBlank(ls.get(7))||!StringUtils.isNumeric(ls.get(7)))throw new BizException("所有导入失败，有学生是否申请教材为空或格式错误,请检查后重试");
            Child child = new Child();
            if(StringUtils.isNotEmpty(ls.get(1))){
                child.setEnglishName(ls.get(1));
            }
            child.setChildName(ls.get(0));
            child.setSex(Integer.valueOf(ls.get(2)));
            User u=userService.getOne(new QueryWrapper<User>().eq("tel_no",ls.get(5)).eq("deleted", 0));
            if(u!=null){
                failList.add(ls.get(5));
                continue;
            }
            Classs classs=classsService.selectClasssForExcel(ls.get(3),ls.get(4),organizationId,schoolId,sysUserId);
            if(classs==null){
                failList.add(ls.get(5));
                continue;
            }
            ChildReq childReq = new ChildReq();
            childReq.setChildName(ls.get(0));
            if(StringUtils.isNotEmpty(ls.get(1))){
                childReq.setEnglishName(ls.get(1));
            }
            childReq.setSex(Integer.valueOf(ls.get(2)));
            childReq.setSchoolId(classs.getSchoolId());
            childReq.setClassId(classs.getId());
            childReq.setTelNo(ls.get(5));
            childReq.setApplyBook(Integer.valueOf(ls.get(7)));
            childReq.setStudentType(Integer.valueOf(ls.get(6)));
            Integer childId=childService.addNewChild(childReq);
            if(childId!=null&&childId.intValue()>0){
                childList.add(child);
            }else {
                failList.add(ls.get(5));
            }
        }
        if(!childList.isEmpty()){
            commonService.saveOperation(request,"学员列表-导入学员,导入成功的条数为："+childList.size());
        }
        return JsonResult.ok(failList.size()+"条数据导入失败！");
    }

    /*@RequestMapping("/export")
    public void exportCallConnection(ChildForm childForm) throws Exception  {
        childForm.setPage(1);
        childForm.setLimit(1000);
        PageResult<ChildResp> r = childService.queryChildList(childForm);
        LinkedHashMap<String, String> headTitles = new LinkedHashMap<>();
        headTitles.put("childName", "地区编码");
        headTitles.put("area_name", "地区");
        headTitles.put("company_name", "公司名称");
        headTitles.put("connection_rate", "5s接通率占比");
        UploadUtils.exportExcel(response,"呼叫养老中心5S接通率占比", headTitles, null);
    }*/

}
